/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.asset.receive.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.dto.receive.ReceiveExcelDTO;
import com.fuyao.cloud.asset.dto.receive.ReceiveSearchDTO;
import com.fuyao.cloud.asset.enums.AssetStatusEnum;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.controller.FlowableController;
import com.fuyao.cloud.common.core.flowable.enums.ProcessStatusEnum;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.mybatis.SpliceQueryWrapper;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.asset.entity.receive.Receive;
import com.fuyao.cloud.asset.receive.service.ReceiveService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 资产领用
 *
 * @author liyue
 * @date 2021-12-16 10:41:00
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/receive")
@Api(value = "receive", tags = "资产领用管理")
public class ReceiveController implements FlowableController {

	private final ReceiveService receiveService;

	/**
	 * 分页查询
	 *
	 * @param page    分页对象
	 * @param receive 资产领用
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('receive_receive_view')")
	public R getReceivePage(Page page, ReceiveSearchDTO receive) {
		return R.ok(receiveService.page(page, SpliceQueryWrapper.spliceSearchCondition(receive),receive));
	}

	/**
	 * 通过id查询资产领用
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('receive_receive_view')")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(receiveService.getById(id));
	}

	/**
	 * 新增资产领用
	 *
	 * @param receive 资产领用
	 * @return R
	 */
	@ApiOperation(value = "新增资产领用", notes = "新增资产领用")
	@SysLog("新增资产领用")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('receive_receive_add')")
	public R save(@RequestBody Receive receive) {
		receiveService.save(receive);
		return R.ok(receive);
	}

	/**
	 * 修改资产领用
	 *
	 * @param receive 资产领用
	 * @return R
	 */
	@ApiOperation(value = "修改资产领用", notes = "修改资产领用")
	@SysLog("修改资产领用")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('receive_receive_edit')")
	public R updateById(@RequestBody Receive receive) {
		return R.ok(receiveService.updateById(receive));
	}

	/**
	 * 通过id删除资产领用
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除资产领用", notes = "通过id删除资产领用")
	@SysLog("通过id删除资产领用")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('receive_receive_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(receiveService.removeById(id));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param receive 查询条件
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('receive_receive_export')")
	public List<ReceiveExcelDTO> export(ReceiveSearchDTO receive) {
		return receiveService.listReceive(SpliceQueryWrapper.spliceSearchCondition(receive), receive.getType());
	}

	@GetMapping("/create")
	@PreAuthorize("@pms.hasPermission('receive_receive_add')")
	public R create(@PathParam("type") String type) {
		return R.ok(this.receiveService.create(type));
	}

	@GetMapping("/edit/{id}")
	@PreAuthorize("@pms.hasPermission('receive_receive_edit')")
	public R edit(@PathVariable("id") Long id) {
		return R.ok(this.receiveService.edit(id));
	}


	@ApiOperation(value = "批量删除资产领用/退库", notes = "批量删除资产领用/退库")
	@SysLog("批量删除资产领用/退库" )
	@DeleteMapping("/batchDelete" )
	@PreAuthorize("@pms.hasPermission('receive_receive_del')" )
	public R batchDelete(@RequestBody List<Long> ids) {
		return receiveService.batchDelete(ids);
	}

	@ApiOperation(value = "起草环节结束回调方法", notes = "起草环节结束回调方法")
	@PostMapping(value = "/draftEndCallback", produces = "application/json")
	@Override
	public R draftEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			Receive receive = this.receiveService.getById(id);
			Assert.isTrue(ObjectUtils.isNotEmpty(receive), String.format("未找到对应的业务数据：%s", id));
			receive.setStatus(AssetStatusEnum.PROCESSING.getCode());
			this.receiveService.approval(receive);
			return R.ok(receive,"修改状态成功");
		}
		return R.ok(CommonConstants.SUCCESS,"起草环节结束回调方法");
	}

	@ApiOperation(value = "回退至起草环节回调方法", notes = "回退至起草环节回调方法")
	@PostMapping(value = "/returnCallback", produces = "application/json")
	@Override
	public R returnCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			Receive receive = this.receiveService.getById(id);
			Assert.isTrue(ObjectUtils.isNotEmpty(receive), String.format("未找到对应的业务数据：%s", id));
			receive.setStatus(AssetStatusEnum.DRAFT.getCode());
			this.receiveService.approval(receive);
			return R.ok(receive,"修改状态成功");
		}
		return R.ok(CommonConstants.SUCCESS,"回退至起草环节回调方法");
	}

	@ApiOperation(value = "流程结束回调方法", notes = "流程结束回调方法")
	@PostMapping(value = "/callback", produces = "application/json")
	@Override
	public R finishEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
		if (params.containsKey("businessKey")) {
			String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
			Receive receive = this.receiveService.getById(id);
			Assert.isTrue(ObjectUtils.isNotEmpty(receive), String.format("未找到对应的业务数据：%s", id));
			String status = params.containsKey(ProcessStatusEnum.ZZ.toString()) ? AssetStatusEnum.INVALID.getCode() : AssetStatusEnum.APPROVE.getCode();
			receive.setStatus(status);
			// 记录出库时间
			receive.setOutTime(LocalDateTime.now());
			this.receiveService.approval(receive);
			return R.ok(receive,"修改状态成功");
		}
		return R.failed("未找到对应的业务数据");
	}
}
